package com.buaa.aiguangxi.controller;

import com.alibaba.fastjson.JSONObject;
import com.buaa.aiguangxi.service.InstanceService;
import com.buaa.aiguangxi.utils.JsonUtil;
import com.buaa.aiguangxi.utils.RandomUtil;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@RestController
public class StatisticsController {

	private final InstanceService instanceService;

	private final RestTemplate restTemplate;

	public StatisticsController(InstanceService instanceService, RestTemplate restTemplate) {
		this.instanceService = instanceService;
		this.restTemplate = restTemplate;
	}

	private static String localDir = "C:/Users/18879/Desktop/model";
//	private String remoteDir = "/py/statics";

	private String remoteDir = "/py/statistics";

	@PostMapping("/create/statistic/train/submit")
	public Map<String, Object> trainSubmit(@RequestBody JSONObject input) throws IOException {
		Map<String, Object> map = new HashMap<>();

		instanceService.addAnInstance(input.getInteger("sceneid"), input.getJSONObject("model").getBoolean("goon") ? 1 : 0, input.getString("name"));

		fakeLossAndAccuracy(map);

		map.put("success", true);
		map.put("msg", "success");
		return map;
	}


	@GetMapping("/execute/statistic/info")
	public Map<String, Object> execute() {
		Map<String, Object> map = new HashMap<>();

//		algorithm
		Map<String, Object> algorithm = new HashMap<>();
		algorithm.put("name", " LR，XGBoost，VAR，LSTM，MTGNN");
		algorithm.put("version", "1.0");
		algorithm.put("author", "BUAA");
		algorithm.put("time", "");
		algorithm.put("last", "");
		map.put("algorithm", algorithm);

//		warning 空
		Map<String, Object> warning = new HashMap<>();
		warning.put("time", new Date());
		warning.put("level", 0);
		warning.put("duration", 0);
		warning.put("content", "");
		map.put("warning", warning);

//		fluent
		Object fluent = restTemplate.getForObject("http://127.0.0.1:5000", Object.class);
		map.put("fluent", fluent);

//		model
		Map<String, Object> model = new HashMap<>();
		fakeLossAndAccuracy(model);
		map.put("model",model);

//		log_str
		map.put("log_str", "544x640 Detection: empty, Done. Volume: 0 IN, 0 OUT. (0.308s)");

		map.put("success", true);
		map.put("msg", "success");
		return map;
	}

	private void fakeLossAndAccuracy(Map map) {
		double[] loss = new double[200];
		double[] accuracy = new double[200];
		RandomUtil.initArray(loss, 0, 0.01);
		RandomUtil.initArray(accuracy, 0.93, 0.98);
		map.put("loss", loss);
		map.put("accuracy", accuracy);
	}

	@GetMapping("/create/statistic/info")
	public Object info() throws IOException {
		return JsonUtil.load(remoteDir, "statistic_info.json");
	}
}
